import {snCreateUIDom, getAppPageConfig} from '../../../../hrpub/common/utils/utils';

import CommonAction from '../../../public/actions/employing/common';
import Constant from './constant';

import {getBusinessInfo, pageTo} from 'nc-lightapp-front';

let businessInfo = getBusinessInfo() || {};

export default class MainAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        if(comp.props.use){
            comp.props.use.form('card','psninfo','oldinfo','newinfo','neworgs','contorgs','execinfo','tailinfo','auditinfo',
            'card_batch', "psninfo_batch", "newinfo_batch", "stapply_mng_org_batch", "contract_mng_org_batch", "exeinfo_batch", "endinfo_batch");
            comp.props.use.editTable('list');
            // comp.props.use.editTable('list');
            comp.props.use.search('query');
        }
    }

    extend = [Constant]

    appConfig = getAppPageConfig()

    // 合并批量新增里的模版信息
    mergeTemplate = (res) => {
        let resource = this.deepCopy(res);
        let batchAdd = resource.batch_add;
        let template = {
            ...resource.template
        };
        Object.keys(batchAdd).forEach((item) => {
            if (item.indexOf('batch') !== -1) {
                template[item] = this.deepCopy(batchAdd[item])
            }
        })

        const tmpList = ['list', 'multiadd'];

        tmpList.forEach((item) => {
            let name = `batchadd${item}`;
            batchAdd[item].code = name;
            template[name] = batchAdd[item];
        });
        template[`card_batch`] = this.deepCopy(batchAdd['card_batch']);
        template[`card_batch`].code = 'card_batch';

        // template[`batchaddcard`] = this.deepCopy(template['card']);
        // template[`batchaddcard`].code = 'batchaddcard';

        template['gridrelation']['batchaddlist'] = {
            srcAreaCode: 'batchaddlist',
            tabRelation: ['batchaddlist']
        };
        // template['formrelation']['batchaddcard'] = [];
        template['formrelation']['card_batch'] = batchAdd['formrelation']['card_batch']
        // 因为批量新增和新增模版不一样，所以复制每一个子表
        // template['formrelation']['card'].forEach((item) => {
        //     let name = `batch${item}`;
        //     template[name] = this.deepCopy(template[item]);
        //     template['formrelation']['batchaddcard'].push(name);
        // });

        return template;
    }

    // 获取多语
    getLanguage = () => {
        const {props} = this.comp;
        const {
            dispatch,
            MultiInit
        } = props;

        MultiInit.getMultiLang({
            moduleId: 'gx6008',
            domainName: 'hrtrn',
            callback: (json, status, init) => {
                this.update({
                    language: this.deepCopy(json)
                })
            }
        });
    }

    //  获取内容页面高度，并且设置表格高度
    getMainTableHeight = () => {
        if (window.getComputedStyle) {
            let app = document.getElementById('app');
            let height = window.getComputedStyle(app).height.replace('px', '');

            this.update({
                pageHeight: height
            });
        }
    }

    // 获取模版信息
    getTemplate = () => {
        const {props, action} = this.comp;
        const {
            meta,
            button,
            dispatch
        } = props;

        snCreateUIDom(this.appConfig, this.getRequest(this.appConfig), (res) => {
            console.log(res);
            let template = this.mergeTemplate(res);
            let template1 = action.pTmp.processTemplate(template);
            let cardFormrelation = template1.formrelation.card;
            let formTemp = {};
            Object.keys(template1).forEach((item) => {
                if(cardFormrelation.includes(item)){
                    formTemp[item]=template1[item]
                }
            })
            this.update({
                context: res.context,
                showOrgRefer: true,
                pageid: res.template.pageid,
                batchAddPageId: res.batch_add.pageid,
                formTemp: formTemp
            });
            meta.setMeta(template1, this.processAfterGetTemplate);
            button.setButtons(res.button);
        });
    }

    // 当模版获取并设置完成之后的回调函数
    processAfterGetTemplate = () => {
        this.getUrlParam();
    }
    widget = () => {
        const {action} = this.comp;
        action.btnAct.changeOrg('widget')
    }
    // 初始化
    didMount = () => {
        this.getTemplate();
        this.getLanguage();
        this.comp.action.btnAct.initPageButton();
        // 统一订阅事件
        this.subscribe();
        this.getMainTableHeight();
        let type = pageTo.getUrlParam('type')
        if (type) {
            setTimeout(() => {
                this.widget()
            }, 200);
        }
    }

    // 获取url数据
    getUrlParam = () => {
        const {props, action} = this.comp;
        const {getUrlParam} = props;

        let scene = getUrlParam('scene');
        if (!scene && getUrlParam('status')) {
            scene = 'approvesce'
        }
        if (scene === 'approvesce') {
            this.update({
                fromApprove: true,
                orgValue: {
                    refpk: businessInfo.groupId
                }
            });
        } else {
            this.update({
                page: 'main'
            });
            return;
        }

        let id = getUrlParam('id');
        let status = getUrlParam('status');
        let selectedRows = [{
            values: {
                pk_hi_stapply: {
                    value: id
                }
            }
        }];

        if (status === 'browse') {
            action.formAct.toBrowsePage(selectedRows);
        } else {
            action.formAct.toEditPage(selectedRows);
        }

    }

    // 卸载
    willUnMount = () => {
        this.pubSub.unSubscribe('getMainTableData');
        this.pubSub.unSubscribe('fileManager');
    }

    // 事件订阅部分
    subscribe = () => {
        const {comp: {action}, pubSub} = this;
        pubSub.subscribe('getMainTableData', (...args) => {
            action.tableAct.getMainTableData(...args);
        });
        pubSub.subscribe('getWidgetTableData', (...args) => {
            action.tableAct.getWidgetTableData(...args);
        });
        pubSub.subscribe('fileManager', (...args) => {
            this.fileManager(...args);
        });
    }

    // 确认查询
    toSearch = () => {
        this.comp.props.dispatch({
            type: 'emp/update',
            payload: {
                hasSearched: true
            }
        });
        this.comp.action.tableAct.getMainTableData({
            hasSearched: true
        });
    }

    // 翻页
    turnPage = (page) => {
        const {props} = this.comp;
        const {
            emp
        } = props;

        if (page === emp.pageInfo.pageIndex) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageIndex: page
        }
        if (emp.widget) {
            this.pubSub.publish('getWidgetTableData', {
                pageInfo: pageInfo
            });
        } else {
            this.pubSub.publish('getMainTableData', {
                pageInfo: pageInfo
            });
        }
    }

    // c改变每页显示条数
    changePageSize = (size) => {
        const {props, action} = this.comp;
        const {
            emp
        } = props;

        if (size === emp.pageInfo.pageSize) {
            return;
        }

        let pageInfo = {
            ...emp.pageInfo,
            pageSize: size
        }
        if (emp.widget) {
            this.pubSub.publish('getWidgetTableData', {
                pageInfo: pageInfo
            });
        } else {
            this.pubSub.publish('getMainTableData', {
                pageInfo: pageInfo
            });
        }
    }

    // 打印
    printTable = () => {
        const {props} = this.comp;
        const {emp, editTable, meta} = props;

        let tableWrapper = document.getElementById('mainTable');

        this.print(tableWrapper, {
            title: emp.language['gx6008-000199'], // 离职办理
            maker: emp.language['gx6008-000068'], // 制作者
            date: emp.language['gx6008-000069'], // 制作日期
            beforeAppend: (data) => {

                data[0].forEach((item) => {
                    delete item[0];
                });
                data[1].forEach((item) => {
                    item.length = item.length - 1;
                });
                return data;
            }
        }, {
            data: editTable.getAllRows('list'),
            tableTmp: meta.getMeta()['list']
        });
    }

    // 输出
    outputTable = () => {
        const {
            props: {
                editTable,
                emp: {
                    language
                },
                meta
            }
        } = this.comp;
        let tableWrapper = document.getElementById('mainTable');
        let tableData = editTable.getAllData('list');

        this.exportHtml(tableWrapper, {
            fileName: language['gx6008-000199'] // '离职办理'
        }, {
            meta: meta.getMeta()['list'],
            data: tableData.rows,
            showIndex: false
        });
    }

    // 福建管理
    fileManager = (selectedRows) => {
        let billId = selectedRows[0].values['pk_hi_stapply'].value;

        this.update({
            fileManagerBillId: billId,
            fileManagerModalVisible: true
        });
    }

    onClose = () => {
        const {props} = this.comp;
        const {dispatch, emp} = props;

        dispatch({
            type: 'emp/update',
            payload: {
                excuteVisible: false
            }
        })
    }
}